#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/10/20 9:04
# @Author  : afraidbenq
# @File    : consumer.py
# @Software: PyCharm
# @Github  : github/afraidbenq
# @Email   : 329189987@qq.com
# @Desc    :
"""
通过数据库或redis或MQ消费策略指令

"""
import os
import re
import time
import sys
import datetime
# 避免导入common报错
sys.path.append("C:\SourcetreeWorkspace\AppiumProject")
sys.path.append("C:\Sourcetree\AppiumProject")
from common import logger
from common import appium_desired
from db.sys_redis import redis_client
from view.ths_view.simulated_view import SimulatedView


class Consumer(object):

    def __init__(self, config_file):
        self.is_work = True
        # 连接redis
        redis_client.init_redis_connect()
        self.redis = redis_client
        # 测试用数据
        # self.redis['YS55VOYDS88SDQ9T:620038:{}'.format(int(time.time()) + 33)] = '{"step":"exit"}'
        # self.redis['YS55VOYDS88SDQ9T:620138:{}'.format(int(time.time()) + 13)] = '{"step":"query"}'
        # self.redis['YS55VOYDS88SDQ9T:620238:{}'.format(int(time.time()) + 23)] = '{"step":"5"}'
        # self.redis['YS55VOYDS88SDQ9T:620028:{}'.format(int(time.time()) + 2)] = '{"step":"2"}'
        # self.redis['YS55VOYDS88SDQ9T:620018:{}'.format(int(time.time()) + 1)] = '{"step":"1"}'
        # self.redis['YS55VOYDS88SDQ9T:620118:{}'.format(int(time.time()) + 1)] = '{"step":"1.5"}'
        # self.redis['YS55VOYDS88SDQ9T:620218:{}'.format(int(time.time()) - 300)] = '{"step":"1.7"}'
        self.message_queue = []
        self.current_key = None
        self.current_step = None
        self.timer = 0
        # 启动driver
        self.driver = appium_desired(config_file)
        self.udid = self.driver.capabilities['desired']['udid']
        # 初始化准备
        self.s = None
        self.check = False
        self.ready()

    def ready(self):
        while True:
            try:
                self.s = SimulatedView(self.driver)
                self.s.enter_simulated_buy()
            except Exception as e:
                logger.error("初始化准备失败！")
                logger.error(e)
                self.driver.close_app()
                self.driver.launch_app()
            else:
                break

    def take_last(self, elem):  # 指定最后时间戳排序
        return elem.split(':')[-1]

    def standby(self):
        while self.is_work:
            try:
                # 消息队列包含N种操作:buy、sale、withdrawal、query、exit、check
                # key: 设备uid:code:时间戳
                # 例子: YS55VOYDS88SDQ9T:601788:1436428326
                # value:
                # {"step": "buy", "name": "光大证券", "code": "601788", "price": 13.82, "amount": 100, "limit_price": 1}
                # {"step": "sale", "name": "比亚迪", "code": "002594", "price": 266.71, "amount": 100, "limit_price": 1}
                # {"step": "withdrawal", "name": "光大证券", "code": "601788", "yes": 0}
                # {"step": "query"}
                # {"step": "exit"}
                # {"step": "standby"}
                # {"step": "check"}
                self.message_queue = self.redis.keys(pattern="send:{}*".format(self.udid))
                # 按时间戳排序 key指定哪个值排序，reverse = True 降序， reverse = False 升序（默认）
                self.message_queue.sort(key=self.take_last, reverse=False)
                logger.info(self.message_queue)
                if len(self.message_queue) > 0:
                    self.current_key = self.message_queue[0]
                    self.current_step = eval(self.redis[self.current_key])
                    if int(self.current_key.split(':')[-1]) < int(time.time()) - 300:
                        logger.info("当前操作key<{}>已过期! 删除处理!".format(self.current_key))
                        logger.info("删除操作{}".format(self.current_step))
                        del self.redis[self.current_key]
                        continue
                    # 执行操作
                    logger.info("执行操作{}".format(self.current_step))
                    if self.current_step["step"] == "buy":
                        logger.info("执行买入")
                        code = self.current_step["code"]
                        name = self.current_step["name"]
                        price = self.current_step["price"]
                        amount = self.current_step["amount"]
                        limit_price = self.current_step["limit_price"]
                        if limit_price:
                            self.s.buy(code, amount=amount)
                        else:
                            self.s.buy(code, price=price, amount=amount)

                    elif self.current_step["step"] == "sale":
                        logger.info("执行卖出")
                        code = self.current_step["code"]
                        name = self.current_step["name"]
                        price = self.current_step["price"]
                        amount = self.current_step["amount"]
                        limit_price = self.current_step["limit_price"]
                        if limit_price:
                            self.s.sale(code, amount=amount)
                        else:
                            self.s.sale(code, price=price, amount=amount)

                    elif self.current_step["step"] == "withdrawal":
                        logger.info("执行撤单")
                        code = self.current_step["code"]
                        name = self.current_step["name"]
                        yes = self.current_step["yes"]

                    elif self.current_step["step"] == "query":
                        logger.info("执行查询")
                        info = self.s.query_position()
                        back_key = self.current_key.replace("send", "back")
                        value = f'{info}'
                        self.redis.set(back_key, value)

                    elif self.current_step["step"] == "check":
                        logger.info("执行设备运行状态检查")
                        back_key = self.current_key.replace("send", "back")
                        check_json = {"check": self.check}
                        value = f'{check_json}'
                        self.redis.set(back_key, value)

                    elif self.current_step["step"] == "exit":
                        logger.info("执行退出")
                        logger.info("删除操作{}".format(self.current_step))
                        del self.redis[self.current_key]
                        self.s.exit()
                        break
                    else:
                        logger.info("操作<{}>未知!".format(self.current_step))
                        logger.info("执行standby...")
                        self.s.standby_loop()
                    # 删除任务
                    logger.info("删除操作{}".format(self.current_step))
                    self.current_step = None
                    self.timer = 0
                    del self.redis[self.current_key]
                else:
                    time.sleep(1)
                    self.timer += 1
                    if self.timer >= 30:
                        self.current_step = {"step": "standby"}
                        logger.info("连续30秒无操作! 执行standby...")
                        self.check = self.s.standby_loop()
                        self.current_step = None
                        self.timer = 0
            except Exception as e:
                logger.error("当前执行步骤：{} 报错！".format(self.current_step))
                logger.error(e)
                self.s.getScreenShot(self.current_step["step"])
                # 先按物理返回键
                self.driver.press_keycode(4)
                logger.info("稍后重试操作{}".format(self.current_step))
                # 报错的步骤继续执行，先不删除，可能第二次执行就成功
                # del self.redis[self.current_key]
        logger.info("设备服务关闭!")


if __name__ == '__main__':
    xq = datetime.datetime.now().weekday()
    if xq in [5, 6]:
        logger.info("今天是周末!去玩吧!")
    else:
        c = Consumer('ths_desired_caps.yaml')
        c.standby()
    # 关闭cmd窗口
    while True:
        cmd_tasklist = os.popen('tasklist /v /fo csv | findstr /i "cmd"').read()
        for i in cmd_tasklist.split('\n'):
            logger.info(i)
            data_list = re.findall('"(.*?)"', i)
            if data_list:
                pid = data_list[1]
                title = data_list[-1]
                if "暂缺" in title or "cmd_client" in title:
                    os.system('taskkill /f /im %s' % pid)
